/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.document.util;

import cn.hutool.core.io.IoUtil;
import com.je.common.base.spring.SpringContextHolder;
import com.je.document.service.impl.FileOperateLocalServiceImpl;
import com.luciad.imageio.webp.WebPReadParam;
import net.coobird.thumbnailator.Thumbnails;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 缩略图工具
 *
 * @author wangmm@ketr.com.cn
 * @date 2019/9/16
 */
public class ThumbnailsUtil {

    /**
     * 生成图片缩略图
     *
     * @param byteArray 文件数据
     * @return byte[] 缩略图数据
     */
    public static byte[] imageThumbnail(String subFolder, byte[] byteArray, String basePath) throws IOException {
        return imageThumbnail(subFolder, IoUtil.toStream(byteArray), byteArray, basePath);
    }

    /**
     * 生成图片缩略图
     *
     * @param in 文件数据
     * @return byte[] 缩略图数据
     */
    public static byte[] imageThumbnail(String subFolder, InputStream in, byte[] byteArray, String basePath) throws IOException {
        FileOperateLocalServiceImpl localFileOperater = SpringContextHolder.getBean("localFileOperater");
        String newFilePath = "/document/temporary.png";
        ByteArrayInputStream inputStream = IoUtil.toStream(byteArray);
        localFileOperater.uploadFile(subFolder, newFilePath, inputStream);
        String type = imgType(in);
        if (!"webp".equals(type)) {
            //初始化字节数组输出流
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            try {
                //缩放并写入输出流
                Thumbnails.of(IoUtil.toStream(byteArray))
                        .size(200, 200)
                        .outputFormat("png")
                        .toOutputStream(out);
                byte[] thumbnailBytes = out.toByteArray();
                return thumbnailBytes;
            } catch (IOException e) {
                throw e;
            } finally {
                IoUtil.close(in);
                File file = new File(basePath + "/" + subFolder + newFilePath);
                file.delete();
                IoUtil.close(inputStream);
                IoUtil.close(out);
            }
        } else {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            //要转换的文件后缀名
            ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();

            WebPReadParam readParam = new WebPReadParam();
            readParam.setBypassFiltering(true);
            ///data/files/local/
//            reader.setInput(new FileImageInputStream(new File(String.valueOf(filePath))));
//            reader.setInput(new FileImageInputStream(new File("/data/files/local" + newFilePath)));
            reader.setInput(new FileImageInputStream(new File(basePath + "/" + subFolder + newFilePath)));

            // Decode the image
            BufferedImage image = reader.read(0, readParam);
            ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(out);
            ImageIO.write(image, "jpg", imageOutputStream);

            //初始化字节数组输出流
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] thumbnailBytes = null;
            try {
                //缩放并写入输出流
                Thumbnails.of(new ByteArrayInputStream(out.toByteArray()))
                        .size(200, 200)
                        .outputFormat("png")
                        .toOutputStream(outStream);
                thumbnailBytes = outStream.toByteArray();
            } catch (IOException e) {

            } finally {
                IoUtil.close(in);
                IoUtil.close(out);
                IoUtil.close(outStream);
                imageOutputStream.close();
                IoUtil.close(inputStream);
                File file = new File(basePath + "/" + subFolder + newFilePath);
                file.delete();
            }
            return thumbnailBytes;
        }

    }

    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //要转换的文件后缀名
        ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();

        WebPReadParam readParam = new WebPReadParam();
        readParam.setBypassFiltering(true);

        // Configure the input on the ImageReader
        reader.setInput(new FileImageInputStream(new File("/Users/wangchao/Downloads/1.png")));

        // Decode the image
        BufferedImage image = reader.read(0, readParam);
        ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(out);
        ImageIO.write(image, "jpg", imageOutputStream);

        //初始化字节数组输出流
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        try {
            //缩放并写入输出流
            Thumbnails.of(new ByteArrayInputStream(out.toByteArray()))
                    .size(200, 200)
                    .outputFormat("png")
                    .toOutputStream(outStream);
            byte[] thumbnailBytes = outStream.toByteArray();
        } catch (IOException e) {

        } finally {
            IoUtil.close(out);
            IoUtil.close(outStream);
        }

        imageOutputStream.close();
    }

    public static String imgType(InputStream inputStream) throws IOException {
        // 读取文件前几位
        byte[] fileHeader = new byte[4];
        int read = inputStream.read(fileHeader, 0, fileHeader.length);
//        inputStream.close();

        // 转为十六进制字符串
        String header = bytes2Hex(fileHeader);

        if (header.contains("FFD8FF")) {
            return "jpg";
        } else if (header.contains("89504E47")) {
            return "png";
        } else if (header.contains("47494638")) {
            return "gif";
        } else if (header.contains("424D")) {
            return "bmp";
        } else if (header.contains("52494646")) {
            return "webp";
        } else if (header.contains("49492A00")) {
            return "tif";
        } else {
            return "unknown";
        }

    }

    public static String bytes2Hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xff);
            sb.append(hex.length() == 2 ? hex : ("0" + hex));
        }
        return sb.toString();
    }
}